package com.turing.post.salesmanage.impl;

import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.account.util.MasterAccountDao;
import com.turing.post.capitalaccounts.util.BankAccountDetail;
import com.turing.post.capitalaccounts.util.BankAccountDetailDao;
import com.turing.post.capitalaccounts.util.SaleCapitalDetail;
import com.turing.post.capitalaccounts.util.SaleCapitalDetailDao;
import com.turing.post.cardmanagement.util.ActivateCard;
import com.turing.post.cardmanagement.util.ActivateCardDao;
import com.turing.post.cardmanagement.util.CardClassic;
import com.turing.post.cardmanagement.util.CardClassicDao;
import com.turing.post.cardtransactions.util.CardTransBusiness;
import com.turing.post.common.util.BlackList;
import com.turing.post.common.util.BlackListDao;
import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.common.util.SysOperLog;
import com.turing.post.common.util.SysOperLogDao;
import com.turing.post.organization.util.IssueCompany;
import com.turing.post.organization.util.IssueCompanyDao;
import com.turing.post.organization.util.IssueFeePolicy;
import com.turing.post.organization.util.IssueFeePolicyBusiness;
import com.turing.post.organization.util.IssueFeePolicyLimit;
import com.turing.post.organization.util.IssueFeePolicyLimitDao;
import com.turing.post.organization.util.SaleBranch;
import com.turing.post.organization.util.SaleBranchDao;
import com.turing.post.organization.util.SysBranch;
import com.turing.post.organization.util.SysBranchDao;
import com.turing.post.organization.util.VoucherBusinessBind;
import com.turing.post.organization.util.VoucherBusinessBindDao;
import com.turing.post.organization.util.VoucherStock;
import com.turing.post.organization.util.VoucherStockDao;
import com.turing.post.organization.util.VoucherStockDetail;
import com.turing.post.organization.util.VoucherStockDetailDao;
import com.turing.post.salesmanage.util.DepositOrder;
import com.turing.post.salesmanage.util.DepositOrderActionDetail;
import com.turing.post.salesmanage.util.DepositOrderActionDetailDao;
import com.turing.post.salesmanage.util.DepositOrderBusiness;
import com.turing.post.salesmanage.util.DepositOrderDao;
import com.turing.post.salesmanage.util.DepositOrderDetail;
import com.turing.post.salesmanage.util.DepositOrderDetailDao;
import com.turing.post.salesmanage.util.DepositOrderPaidDetail;
import com.turing.post.salesmanage.util.DepositOrderPaidDetailDao;
import com.turing.post.salesmanage.util.DepositOrderSalesDetail;
import com.turing.post.salesmanage.util.DepositOrderSalesDetailDao;
import com.turing.post.salesmanage.util.PersonalCustom;
import com.turing.post.salesmanage.util.PersonalCustomDao;
import com.turing.post.salesmanage.util.SaleOrderPaidDetail;
import com.turing.post.salesmanage.util.SalesManageApplicationException;
import com.turing.post.salesmanage.util.SalesManageRespCode;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

/**
 * 充值单业务实现
 * 
 * @author zxp
 */
@Stateless(mappedName = "salesmanage.impl.DepositOrderBusinessImpl")
@Remote
@Local
public class DepositOrderBusinessImpl implements DepositOrderBusiness {

	@EJB(mappedName = "common.impl.SysOperLogDaoImpl")
	private SysOperLogDao sysOperLogDaoImpl;

	@EJB(mappedName = "common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao commonDaoImpl;

	@EJB(mappedName = "organization.impl.IssueCompanyDaoImpl")
	private IssueCompanyDao issueCompanyDaoImpl;

	@EJB(mappedName = "salesmanage.impl.DepositOrderDaoImpl")
	private DepositOrderDao depositOrderDaoImpl;

	@EJB(mappedName = "salesmanage.impl.DepositOrderActionDetailDaoImpl")
	private DepositOrderActionDetailDao depOrderAcDeDaoImpl;

	@EJB(mappedName = "salesmanage.impl.DepositOrderSalesDetailDaoImpl")
	private DepositOrderSalesDetailDao depOrderDaoImpl;

	@EJB(mappedName = "salesmanage.impl.DepositOrderPaidDetailDaoImpl")
	private DepositOrderPaidDetailDao depositOrderPaidDetailDaoImpl;

	@EJB(mappedName = "salesmanage.impl.DepositOrderDetailDaoImpl")
	private DepositOrderDetailDao depositOrderDetailDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.CardClassicDaoImpl")
	private CardClassicDao cardClassicDaoImpl;

	@EJB(mappedName = "salesmanage.impl.PersonalCustomDaoImpl")
	private PersonalCustomDao personalCustomDaoImpl;

	@EJB(mappedName = "common.impl.BlackListDaoImpl")
	private BlackListDao blackListDaoImpl;

	@EJB(mappedName = "organization.impl.SaleBranchDaoImpl")
	private SaleBranchDao saleBranchDaoImpl;

	@EJB(mappedName = "organization.impl.SysBranchDaoImpl")
	private SysBranchDao sysBranchDaoImpl;

	@EJB(mappedName = "capitalaccounts.impl.SaleCapitalDetailDaoImpl")
	private SaleCapitalDetailDao saleCapitalDetailDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.ActivateCardDaoImpl")
	private ActivateCardDao activateCardDaoImpl;

	@EJB(mappedName = "organization.impl.IssueFeePolicyBusinessImpl")
	private IssueFeePolicyBusiness issueFeePolicyBusinessImpl;

	@EJB(mappedName = "cardtransactions.impl.CardTransBusinessImpl")
	private CardTransBusiness cardTransBusinessImpl;

	@EJB(mappedName = "organization.impl.VoucherBusinessBindDaoImpl")
	private VoucherBusinessBindDao voucherBusinessBindImpl;

	@EJB(mappedName = "organization.impl.VoucherStockDaoImpl")
	private VoucherStockDao voucherStockDaoImpl;

	@EJB(mappedName = "organization.impl.VoucherStockDetailDaoImpl")
	private VoucherStockDetailDao voucherStockDetailDaoImpl;

	@EJB(mappedName = "organization.impl.IssueFeePolicyLimitDaoImpl")
	private IssueFeePolicyLimitDao issueFeePolicyLimitDaoImpl;

	@EJB(mappedName = "capitalaccounts.impl.BankAccountDetailDaoImpl")
	private BankAccountDetailDao bankAccountDetailDaoImpl;

	@EJB(mappedName = "salesmanage.impl.DepositOrderBusinessImpl")
	private DepositOrderBusiness depositOrderBusinessImpl;

	/**
	 * 异常抛出方法
	 * 
	 * @param error
	 * @throws PCPSApplicationException
	 */
	private void errException(String error) throws PCPSApplicationException {
		throw new SalesManageApplicationException(
				SalesManageApplicationException.ERRCODE_CATEGORY_APPLICATION,
				SalesManageRespCode.DEPOSIT_EXCEPTIONCODE, error);
	}

	/**
	 * 判断充值单付款是否包含现金
	 * 
	 * @param saleOrders
	 * @return
	 */
	@Override
	public boolean checkCashDepositOrder(BigInteger[] depositOrderIds) {
		boolean result = false;
		List<DepositOrderPaidDetail> sopdList = null;
		if (depositOrderIds == null || depositOrderIds.length < 1) {
			return result;
		}
		for (BigInteger b : depositOrderIds) {
			sopdList = depositOrderPaidDetailDaoImpl
					.getDepositOrderPaidDetailListByDepositOrderId(b);
			if (sopdList != null && sopdList.size() > 0) {
				// 销售单购卡中有现金付款
				for (DepositOrderPaidDetail sopd : sopdList) {
					// 现金购卡
					if (sopd.getPaidType().equals(
							DepositOrderPaidDetail.DEPOSITOPD_PAIDTYPE_CASH)) {
						result = true;
					}
				}
			}
		}
		return result;
	}

	/**
	 * 充值单打包上送
	 * 
	 * @param webInput
	 * @param saleOrderIds
	 * @throws PCPSApplicationException
	 */
	@Override
	public void updateDepositOrderCommitVoucherNo(PCPSWebInput webInput,
			BigInteger[] depositOrderIds, BigInteger bankAccDetailId)
			throws PCPSApplicationException {
		if (webInput == null || PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			errException("操作员或归属机构为空!");
		}
		if (depositOrderIds == null || depositOrderIds.length < 1) {
			errException("未选择需要上送的充值单!");
		}
		DepositOrder so = null;
		String res = "";
		BigInteger allCash = BigInteger.ZERO;// 总现金金额
		List<DepositOrderPaidDetail> sopdList = null;
		List<DepositOrder> orderList = new ArrayList<DepositOrder>();
		HashMap<BigInteger, BigInteger> map = new HashMap<BigInteger, BigInteger>();
		for (BigInteger b : depositOrderIds) {
			so = depositOrderDaoImpl.getDepositOrderByDepositOrderId(b);
			orderList.add(so);
			sopdList = depositOrderPaidDetailDaoImpl
					.getDepositOrderPaidDetailListByDepositOrderId(b);
			if (sopdList != null && sopdList.size() > 0) {
				// 充值单购卡中有现金付款
				for (DepositOrderPaidDetail sopd : sopdList) {
					// 现金购卡
					if (sopd.getPaidType().equals(
							DepositOrderPaidDetail.DEPOSITOPD_PAIDTYPE_CASH)) {
						map.put(so.getDepositOrderId(), so.getDepositOrderId());
						allCash = allCash.add(sopd.getPaidAmount());
					}
				}
			}
			res += b.toString() + ",";
		}
		// if (allCash.compareTo(BigInteger.ZERO) > 0) {
		// if (bankAccDetailId == null) {
		// errException("打包提交充值单中含有现金充值，必须录入现金上缴流水号!");
		// }
		// BankAccountDetail bad = bankAccountDetailDaoImpl
		// .getBankAccountDetailByID(bankAccDetailId);
		// if (bad == null) {
		// errException("输入的现金上缴入账流水号" + bankAccDetailId + "系统中不存在!");
		// }
		// if (allCash.compareTo(bad.getVoucherAmount()) > 0) {
		// errException("打包提交充值单现金充值总金额" + get100(allCash) + "不可大于现金上缴金额"
		// + get100(bad.getVoucherAmount()));
		// }
		// }
		for (DepositOrder dep : orderList) {
			// 含有现金购卡充值单设置现金上缴凭证号
			// if (map.get(dep.getDepositOrderId()) != null) {
			// dep.setBankAccDetailId(bankAccDetailId);
			// }
			// 充值单状态迁移明细
			insertDepositOrderActionDetail(dep.getDepositOrderId(), webInput
					.getOperId(), dep.getOrderStatus(),
					DepositOrder.DEPORDER_ORDERSTATUS_Send,
					DepositOrderActionDetail.DEPOSITOAD_ACTIONTYPE_Send,
					"打包上送充值单");
			dep.setOrderStatus(DepositOrder.DEPORDER_ORDERSTATUS_Send);
			// 修改
			depositOrderDaoImpl.updateDepositOrder(so);
		}
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Add, "充值单打包上送", "充值单流水号："
						+ res.substring(0, res.length() - 1));
	}

	// 充值单资金审核
	@SuppressWarnings("unchecked")
	@Override
	public void authDepositOrderMoney(PCPSWebInput webInput,
			BigInteger[] depositOrderIds) throws PCPSApplicationException {
		if (webInput == null || PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			errException("操作员或归属机构为空!");
		}
		if (depositOrderIds == null || depositOrderIds.length < 1) {
			errException("未选择审核的充值单!");
		}
		for (BigInteger b : depositOrderIds) {
			depositOrderBusinessImpl.authOneDepositOrderMoney(webInput, b);
		}

	}

	// 单个充值单资金审核
	@Override
	public void authOneDepositOrderMoney(PCPSWebInput webInput, BigInteger b)
			throws PCPSApplicationException {
		if (webInput == null || PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			errException("操作员或归属机构为空!");
		}
		DepositOrder so = depositOrderDaoImpl
				.getDepositOrderByDepositOrderId(b);
		if (!so.getOrderStatus().equals(DepositOrder.DEPORDER_ORDERSTATUS_Send)) {
			errException("充值单" + so.getSaleOrderSeqNo() + "状态不为已上送状态!");
		}
		SaleBranch sb = saleBranchDaoImpl.getSaleBranchBySaleBranchNo(so
				.getSaleBranchNo());
		// 充值单付款信息列表
		List<DepositOrderPaidDetail> sodpList = depositOrderPaidDetailDaoImpl
				.getDepositOrderPaidDetailListByDepositOrderId(b);
		// 充值单现金付款
		BigInteger cashAll = BigInteger.ZERO;
		// 充值单现金手续费金额合计
		BigInteger feeAll = BigInteger.ZERO;
		// 充值单转账付款
		BigInteger tranAll = BigInteger.ZERO;
		// 循环销充值付款信息
		DepositOrderPaidDetail sopd = null;
		BankAccountDetail tranBad = null;
		boolean tag = false;
		// 先处理转账类付款信息
		for (int i = 0; i < sodpList.size(); i++) {
			sopd = sodpList.get(i);
			// 非现金转账购卡付款信息
			if (!sopd.getPaidType().equals(
					SaleOrderPaidDetail.PAIDDETAIL_PAIDTYPE_CASH)) {
				tranBad = bankAccountDetailDaoImpl
						.getBankAccountDetailByID(sopd.getBankAccDetailId());
				if (!tranBad.getStauts().equals(
						BankAccountDetail.STATUS_AUTOCHECK)
						&& !tranBad.getStauts().equals(
								BankAccountDetail.STATUS_MANUALLYCHECK)) {
					errException("银行凭证号" + tranBad.getVoucherNo() + "对应记账金额"
							+ get100(tranBad.getVoucherAmount()) + "未核对!");
				}
				if (tranBad.getVoucherAmount().compareTo(
						sopd.getPaidAmount().add(tranBad.getDebitAmount())) < 0) {
					errException("银行凭证号"
							+ tranBad.getVoucherNo()
							+ "对应记账记录凭证金额"
							+ get100(tranBad.getVoucherAmount())
							+ "不可小于充值单转账付款金额"
							+ get100(sopd.getPaidAmount())
							+ "与累计借方发生额"
							+ get100(tranBad.getDebitAmount())
							+ "之和"
							+ get100(sopd.getPaidAmount().add(
									tranBad.getDebitAmount())));
				}
				tranBad.setDebitAmount(tranBad.getDebitAmount().add(sopd.getPaidAmount()));// 银行入账流水累计贷方发生额;
				bankAccountDetailDaoImpl.modifyBankAccountDetail(tranBad);// 每次更新转账银行入账流水贷方发生额
				tranAll = tranAll.add(sopd.getPaidAmount());// 充值单转账金额合计
			} else {
				tag = true;// 含有现金付款
				// 充值单现金付款信息
				if (DepositOrderPaidDetail.PAIDDETAIL_paidClass_sale
						.equals(sopd.getPaidClass())) {// 只合计现金销售款
					cashAll = cashAll.add(sopd.getPaidAmount());// 充值单现金金额合计
				} else if (DepositOrderPaidDetail.PAIDDETAIL_paidClass_fee
						.equals(sopd.getPaidClass())) {
					feeAll = feeAll.add(sopd.getPaidAmount());// 充值单现金手续费金额合计
				}
			}
		}
		if (tag) {
			// sb.getAlreadyCheckCash()只含有销售款和充值款
			if (sb.getAlreadyCheckCash().compareTo(cashAll) < 0) {
				errException("销售机构已核实资金金额" + get100(sb.getAlreadyCheckCash())
						+ "不可小于充值单" + so.getSaleOrderSeqNo() + "现金充值款金额合计"
						+ get100(cashAll));
			}
			// 更新销售机构
			sb.setAlreadyCheckCash(sb.getAlreadyCheckCash().subtract(cashAll));
			saleBranchDaoImpl.updateSaleBranch(sb);
		}
		// 销售单已核实资金
		so.setTotalCheckAmount(tranAll.add(cashAll).add(feeAll));
		so.setOrderStatus(DepositOrder.SaleOrder_OrderStatus_AuthMoney);
		so.setRemark(PCPSUtil.isEmpty(so.getRemark()) ? "" : so.getRemark()
				+ " 充值单资金已审核");
		// 销售单状态迁移明细
		insertDepositOrderActionDetail(b, webInput.getOperId(),
				DepositOrder.DEPORDER_ORDERSTATUS_Send,
				DepositOrder.SaleOrder_OrderStatus_AuthMoney,
				DepositOrderActionDetail.DEPOSITOAD_ACTIONTYPE_AuthMoney,
				"充值单资金审核");
		depositOrderDaoImpl.updateDepositOrder(so);
	}

	// 创建批量充值单
	@SuppressWarnings("unchecked")
	@Override
	public DepositOrder createDepositOrder(PCPSWebInput webInput,
			DepositOrder depositOrder, List<DepositOrderDetail> cardDetailList,
			List<DepositOrderSalesDetail> depSalesDetail,
			List<DepositOrderPaidDetail> depPaidDetail)
			throws PCPSApplicationException {
		// 充值单信息=============
		depositOrder = getDepositOrder(webInput, depositOrder);
		// 发卡商
		IssueCompany ic = issueCompanyDaoImpl
				.getIssueCompanyByIssueCompanyNo(PCPSUtil
						.getICNoByBranchNo(depositOrder.getSaleBranchNo()));
		// 发卡商
		// 判断是否为日终(交易)状态
		if (ic == null
				|| ic.getStatus().equals(
						IssueCompany.ISSUECOMPANY_NORMAL_ENDDAY)) {
			errException("充值单所在机构未有归属发卡商或发卡商正在日终禁止充值!");
		}
		// 充值时间
		Date now = commonDaoImpl.getDatabaseSysTime();
		depositOrder.setTranDate(ic.getTranDate());
		depositOrder.setDepositTime(now);
		// 充值单售卡信息=============
		List<DepositOrderDetail> insertDodList = new ArrayList<DepositOrderDetail>();
		DepositOrderDetail insertdod = null;
		BigInteger totalSaleAmount = BigInteger.ZERO;// 充值单总充值金额
		if (cardDetailList.size() < 1) {
			errException("充值单未录入充值信息信息!");
		}
		// 手续费
		BigInteger allFee = BigInteger.ZERO;
		IssueFeePolicy ifp = null;
		// 充值卡详细信息
		for (DepositOrderDetail dod : cardDetailList) {
			insertdod = getDepositOrderDetail(dod, depositOrder.getBtnStatus(),
					ic.getEachCardBalanceLimit(), ic.getEachCardOwnerLimit(),
					ic.getNonDirectSaleLimit());
			// 每张卡单独计算手续费
			ifp = issueFeePolicyBusinessImpl.calculateCardHolderFee(ic
					.getIssueCompanyNo(), depositOrder.getSaleBranchNo(),
					IssueFeePolicy.IFPolicy_busiType_deposit, null, insertdod
							.getCardNo(), insertdod.getCardFaceId(), insertdod
							.getCardClassicId(), null, ic.getTranDate(),
					insertdod.getDepositAmount(), null);
			totalSaleAmount = totalSaleAmount.add(dod.getDepositAmount());
			allFee = allFee.add(ifp.getFee());
			insertDodList.add(insertdod);
		}

		// 手续费上下限
		IssueFeePolicyLimit ifpl = issueFeePolicyLimitDaoImpl
				.getIssueFeePolicyLimitByCompNoAndTypeForEffective(ic
						.getIssueCompanyNo(),
						IssueFeePolicy.IFPolicy_busiType_deposit);
		if (ifpl != null) {
			// 上限
			if (ifpl.getFeeUpperLimit().compareTo(BigInteger.ZERO) > 0) {
				if (allFee.compareTo(ifpl.getFeeUpperLimit()) > 0) {
					allFee = ifpl.getFeeUpperLimit();
				}
			}
			// 下限
			if (ifpl.getFeeLowerLimit().compareTo(BigInteger.ZERO) > 0) {
				if (allFee.compareTo(ifpl.getFeeLowerLimit()) < 0) {
					allFee = ifpl.getFeeLowerLimit();
				}
			}
		}

		// 充值单销售员信息=============
		BigInteger allSalesAmount = BigInteger.ZERO;// 营销金额
		for (DepositOrderSalesDetail dosd : depSalesDetail) {
			allSalesAmount = allSalesAmount.add(dosd.getSalesAmount());
		}
		if (depSalesDetail.size() > 0) {
			if (allSalesAmount.compareTo(totalSaleAmount) != 0) {
				errException("充值单营销员营销金额" + get100(allSalesAmount) + "和充值单充值金额"
						+ get100(totalSaleAmount) + "不符!");
			}
		}
		// 充值单付款信息=============
		List<DepositOrderPaidDetail> insertDopdList = new ArrayList<DepositOrderPaidDetail>();
		HashMap<Integer, SaleCapitalDetail> scdMap = new HashMap<Integer, SaleCapitalDetail>();
		SaleCapitalDetail scd = null;
		DepositOrderPaidDetail insertDopd = null;
		BigInteger alreayPaidAmount = BigInteger.ZERO;// 充值单总付款金额
		BigInteger paidAllFee = BigInteger.ZERO;// 充值单总付款手续费金额
		Integer cashAll = 0;// 现金总付款
		HashMap<BigInteger, BigInteger> bankAccDetailIdMap = new HashMap<BigInteger, BigInteger>();
		// 转账付款合计
		BigInteger tranAmount = BigInteger.ZERO;
		for (int i = 0; i < depPaidDetail.size(); i++) {
			insertDopd = getDepositOrderPaidDetail(webInput, depPaidDetail
					.get(i));
			insertDopd.setTranDate(ic.getTranDate());// 账务日期
			insertDopd.setTranTime(now);// 付款时间
			// 手续费付款金额
			if (insertDopd.getPaidClass().equals(
					DepositOrderPaidDetail.PAIDDETAIL_paidClass_fee)) {
				paidAllFee = paidAllFee.add(insertDopd.getPaidAmount());
			}
			alreayPaidAmount = alreayPaidAmount.add(insertDopd.getPaidAmount());
			scd = getSaleCapitalDetail(depPaidDetail.get(i), ic, depositOrder
					.getSaleBranchNo(), webInput);
			if (scd != null) {
				scdMap.put(i, scd);
				cashAll += Integer.parseInt(scd.getCashDeposit().toString());
			} else {
				scdMap.put(i, null);
			}
			insertDopdList.add(insertDopd);
			// 转账付款
			if (!insertDopd.getPaidType().equals(
					DepositOrderPaidDetail.DEPOSITOPD_PAIDTYPE_CASH)) {
				tranAmount = tranAmount.add(insertDopd.getPaidAmount());
				// 银行转账凭证号
				bankAccDetailIdMap.put(insertDopd.getBankAccDetailId(),
						insertDopd.getBankAccDetailId());
			}
		}
		BigInteger voucherAmount = BigInteger.ZERO;
		// 银行转账凭证号
		for (Iterator<?> it = bankAccDetailIdMap.entrySet().iterator(); it
				.hasNext();) {
			Map.Entry e = (Map.Entry) it.next();
			BankAccountDetail bad = bankAccountDetailDaoImpl
					.getBankAccountDetailByID(new BigInteger(e.getKey()
							.toString()));
			voucherAmount = voucherAmount.add(bad.getVoucherAmount());
			bad.setStauts(BankAccountDetail.STATUS_NOCHECK);// 创建时状态为9
			// ，保存时该为2未核实状态
			bankAccountDetailDaoImpl.modifyBankAccountDetail(bad);
		}
		if (voucherAmount.compareTo(tranAmount) < 0) {
			errException("客户购卡银行转账总金额" + get100(voucherAmount)
					+ "不可小于充值单付款转账总金额" + get100(tranAmount) + "!");
		}

		// 转账提醒
		if (depositOrder.getBuyerType().equals(
				DepositOrder.DEPORDER_BUYERTYPE_PERSON)) {
			if (ic.getPersonTransferLimit() > 0) {
				if (cashAll > ic.getPersonTransferLimit()) {
					errException("个人充值现金付款" + cashAll / 100 + "超过发卡商转账上限"
							+ ic.getPersonTransferLimit() / 100 + ",必须转账!");
				}
			}

		}
		if (depositOrder.getBuyerType().equals(
				DepositOrder.DEPORDER_BUYERTYPE_COMPANY)) {
			if (ic.getOrganizeTransferLimit() > 0) {
				if (cashAll > ic.getOrganizeTransferLimit()) {
					errException("单位充值现金付款" + cashAll / 100 + "超过发卡商转账上限"
							+ ic.getOrganizeTransferLimit() / 100 + ",必须转账!");
				}
			}
		}
		// 充值转账
		if (ic.getDepositTransferLimit().compareTo(BigInteger.ZERO) > 0) {
			if (cashAll > ic.getDepositTransferLimit().intValue()) {
				errException("充值现金付款" + cashAll / 100 + "超过发卡商转账上限"
						+ get100(ic.getDepositTransferLimit()) + ",必须转账!");
			}

		}

		// 设置充值单充值金额
		depositOrder.setTotalDepositAmount(totalSaleAmount);
		// 计算手续费
		depositOrder.setFee(allFee);
		// 设置充值单总付款金额
		depositOrder.setAlreayPaidAmount(alreayPaidAmount);
		boolean feeAuthOper = false;// 手续费优惠授权
		// 实际手续费
		if (depositOrder.getFeeAuthOperId() != null
				&& depositOrder.getFeeAuthOperId().compareTo(BigInteger.ZERO) > 0) {
			if (alreayPaidAmount.compareTo(totalSaleAmount.add(depositOrder
					.getFactFee())) != 0) {
				errException("充值单应付款和实付款不一致!<br/>充值款："
						+ get100(totalSaleAmount.add(depositOrder.getFactFee()))
						+ "<br/>" + PCPSUtil.first_Blank + "打折后应收手续费："
						+ get100(depositOrder.getFactFee()));
			}
			if (paidAllFee.compareTo(depositOrder.getFactFee()) != 0) {
				errException("充值单付款手续费和打折后应收手续费不相符" + get100(paidAllFee));
			}
			feeAuthOper = true;
		} else {
			if (alreayPaidAmount.compareTo(totalSaleAmount.add(allFee)) != 0) {
				errException("充值单应付款和实付款不一致!<br/>充值款："
						+ get100(totalSaleAmount.add(allFee)) + "<br/>"
						+ PCPSUtil.first_Blank + "手续费：" + get100(allFee));
			}
			if (paidAllFee.compareTo(depositOrder.getFee()) != 0) {
				errException("充值单付款手续费" + get100(paidAllFee) + "计算手续费不相符"
						+ get100(depositOrder.getFee()));
			}
			depositOrder.setFactFee(depositOrder.getFee());
		}
		boolean autherOper = false;// 大额授权
		// 校验是否输入柜员店长密码
		if (ic.getOrderAmountLimit().compareTo(BigInteger.ZERO) > 0
				&& alreayPaidAmount.compareTo(ic.getOrderAmountLimit()) > 0) {
			if (depositOrder.getAutherOperId() == null) {
				errException("充值单金额大于" + get100(ic.getOrderAmountLimit())
						+ ",请销售机构主管未授权!");
			}
			if (depositOrder.getAutherOperId().compareTo(webInput.getOperId()) == 0) {
				errException("充值单授权人不能为销售员!");
			}
			autherOper = true;
		}
		// 销售单主键
		BigInteger depositOrderId = commonDaoImpl.getUniqueIntegerKey();
		depositOrder.setDepositOrderId(depositOrderId);
		// 充值单状态
		depositOrder.setOrderStatus(DepositOrder.DEPORDER_ORDERSTATUS_HAVEPAID);
		// 业务单号
		depositOrder.setSaleOrderSeqNo(commonDaoImpl.getOrderNumber(ic
				.getTranDate(), depositOrder.getSaleBranchNo()));
		String branchNo = depositOrder.getSaleBranchNo();
		depositOrder.setDepositType(DepositOrder.DEPORDER_DEPOSITTYPE_MORE);
		// 插入充值单
		depositOrderDaoImpl.insertDepositOrder(depositOrder);
		// 插入售卡明细
		for (DepositOrderDetail dod : insertDodList) {
			dod.setDepositOrderId(depositOrderId);
			depositOrderDetailDaoImpl.insertDepositOrderDetail(dod);
		}
		// 插入销售员明细
		for (DepositOrderSalesDetail dosd : depSalesDetail) {
			dosd.setDepositOrderId(depositOrderId);
			depOrderDaoImpl.insertDepositOrderSalesDetail(dosd);
		}
		// 插入销售单付款明细
		SaleCapitalDetail insertScd = null;
		DepositOrderPaidDetail insertDo = null;
		BigInteger insertId = BigInteger.ZERO;
		BigInteger paidCash = BigInteger.ZERO;
		for (int i = 0; i < insertDopdList.size(); i++) {
			insertDo = insertDopdList.get(i);
			insertId = commonDaoImpl.getUniqueIntegerKey();
			insertDo.setDepositOrderPaidId(insertId);
			insertDo.setDepositOrderId(depositOrderId);
			depositOrderPaidDetailDaoImpl
					.insertDepositOrderPaidDetail(insertDo);
			insertScd = scdMap.get(i);
			if (insertScd != null) {
				paidCash = paidCash.add(insertDo.getPaidAmount());
				insertScd.setTicketId(insertId);// 相关业务单ID
				insertScd.setTranTime(now);// 交易时间
				saleCapitalDetailDaoImpl.insertSaleCapitalDetail(insertScd);
			}
		}
		// 修改销售商分支机构（SaleBranch）现金库存
		SaleBranch sb = saleBranchDaoImpl.getSaleBranchForUpdate(branchNo);
		if (sb == null) {
			errException("销售商分支机构“" + branchNo + "”未找到!");
		}
		sb.setCash(sb.getCash().add(paidCash));
		saleBranchDaoImpl.updateSaleBranch(sb);
		// boolean feeAuthOper=false;//手续费优惠授权
		if (feeAuthOper) {
			sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
					SysOperLog.operType_Add, "充值单手续费优惠授权", "充值单流水号："
							+ depositOrderId);
		}
		// boolean autherOper=false;//大额授权
		if (autherOper) {
			sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
					SysOperLog.operType_Add, "充值单大额授权", "充值单流水号："
							+ depositOrderId);
		}
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Add, "创建充值单业务", "创建充值单业务，充值单号"
						+ depositOrderId);
		// 充值单记帐
		cardTransBusinessImpl.AccountDepositOrder(webInput, depositOrderId,
				webInput.getOperId());
		return depositOrder;
	}

	private String get100(BigInteger a) {
		DecimalFormat numf = new DecimalFormat();
		double d = Double.parseDouble(a.toString()) / 100;
		numf.applyPattern("#,###,###,##0.00");
		if (d == 0)
			return "0.00";
		else
			return numf.format(d);
	}

	// 充值单撤销
	@Override
	public DepositOrder cancelDepositOrder(PCPSWebInput webInput,
			DepositOrder depositOrder) throws PCPSApplicationException {
		if (webInput == null || webInput.getOperId() == null
				|| PCPSUtil.isEmpty(webInput.getOperBranchNo())
				|| depositOrder == null) {
			errException("操作员或充值单参数为空!");
		}
		// 发卡商
		IssueCompany ic = issueCompanyDaoImpl
				.getIssueCompanyByIssueCompanyNo(PCPSUtil
						.getICNoByBranchNo(depositOrder.getSaleBranchNo()));
		String cancelRemark = depositOrder.getRemark();
		// 发卡商
		// 判断是否为日终(交易)状态
		if (ic == null
				|| ic.getStatus().equals(
						IssueCompany.ISSUECOMPANY_NORMAL_ENDDAY)) {
			errException("充值单所在机构未有归属发卡商或发卡商正在日终禁止撤销充值!");
		}
		// 充值单
		DepositOrder _depOrder = depositOrderDaoImpl
				.getDepositOrderByDepositOrderId(depositOrder
						.getDepositOrderId());
		if (_depOrder == null) {
			_depOrder = depositOrderDaoImpl
					.getDepositOrderBySaleOrderSeqNo(depositOrder
							.getSaleOrderSeqNo());
		}
		if (_depOrder == null) {
			errException("充值单号输入有误,未找到所撤充值单!");
		}
		// 非本人不可撤销
		if (webInput.getOperId().compareTo(_depOrder.getOperId()) != 0) {
			errException("充值单只可由创建人撤销!");
		}
		SaleBranch sb = saleBranchDaoImpl.getSaleBranchBySaleBranchNo(webInput
				.getOperBranchNo());
		if (sb.getDayOff().equals(SaleBranch.In_DayOff)) {
			errException("销售机构“" + sb.getSaleBranchName() + "”已经日结!");
		}
		BigInteger depositOrderId = _depOrder.getDepositOrderId();
		// if (_depOrder.getOrderStatus().equals(
		// DepositOrder.DEPORDER_ORDERSTATUS_HAVERECHARGE)) {
		// // 充值单记帐撤销
		// cardTransBusinessImpl.CancelAccountDepositOrder(webInput,
		// depositOrderId, webInput.getOperId(), cancelRemark);
		// }

		if (!_depOrder.getOrderStatus().equals(
				DepositOrder.DEPORDER_ORDERSTATUS_HAVEPAID)) {
			errException("已提交上送的充值单不可撤销!");
		}
		// 销售时间
		Date now = commonDaoImpl.getDatabaseSysTime();
		// 设置充值单状态为已取消
		_depOrder.setOrderStatus(DepositOrder.DEPORDER_ORDERSTATUS_CANCEL);

		// List<DepositOrderDetail> cardDetailList = depositOrderDetailDaoImpl
		// .getDepositOrderDetailListByDepositOrderId(depositOrderId);
		// if (cardDetailList != null && cardDetailList.size() > 0) {
		// DepositOrderDetail insertDod = null;
		// // 充值卡详细信息
		// for (DepositOrderDetail dod : cardDetailList) {
		// insertDod = new DepositOrderDetail();
		// insertDod.setDepositOrderId(depositOrderId);
		// insertDod.setBatchNo(dod.getBatchNo());
		// insertDod.setCardSeqNo(dod.getCardSeqNo());
		// insertDod.setCardNo(dod.getCardNo());
		// insertDod.setCustomId(dod.getCustomId());
		// insertDod.setDepositAmount(BigInteger.ZERO.subtract(dod
		// .getDepositAmount()));
		// depositOrderDetailDaoImpl.insertDepositOrderDetail(insertDod);
		// }
		// }
		// 现金付款
		BigInteger paidCash = BigInteger.ZERO;
		// 充值单付款信息=============
		List<DepositOrderPaidDetail> dodPaidList = depositOrderPaidDetailDaoImpl
				.getDepositOrderPaidDetailListByDepositOrderId(depositOrderId);
		if (dodPaidList != null && dodPaidList.size() > 0) {
			DepositOrderPaidDetail insertPaid = null;
			BigInteger insertPaidId = null;
			for (DepositOrderPaidDetail paid : dodPaidList) {
				insertPaidId = commonDaoImpl.getUniqueIntegerKey();
				insertPaid = new DepositOrderPaidDetail();
				insertPaid.setDepositOrderPaidId(insertPaidId);// 销售单付款ID
				insertPaid.setTranDate(ic.getTranDate());// 账务日期
				insertPaid.setTranTime(now);// 付款时间
				insertPaid.setDepositOrderId(depositOrderId);// 充值单ID
				insertPaid.setPaidType(paid.getPaidType());// 付款方式
				insertPaid.setPaidClass(paid.getPaidClass());// 付款类型
				insertPaid.setPaidAmount(BigInteger.ZERO.subtract(paid
						.getPaidAmount()));// 付款金额
				insertPaid.setPayeeAccountId(paid.getPayeeAccountId());// 收款人ID
				insertPaid.setPaidAccountId(paid.getPaidAccountId()); // 付款人ID
				insertPaid.setVoucherNo(paid.getVoucherNo());// 凭证号
				insertPaid.setVoucherRemark(paid.getVoucherRemark());// 凭证摘要
				insertPaid.setVoucherImageId(paid.getVoucherImageId());// 凭证图片Id
				insertPaid.setOperId(webInput.getOperId());
				insertPaid.setCancelDepositOrderPaidId(paid
						.getDepositOrderPaidId());
				insertPaid.setRemark(paid.getRemark());
				// 新插入付款撤销信息
				depositOrderPaidDetailDaoImpl
						.insertDepositOrderPaidDetail(insertPaid);
				// 修改前付款信息
				paid.setCancelDepositOrderPaidId(insertPaidId);
				if (paid.getPaidType().equals(
						DepositOrderPaidDetail.DEPOSITOPD_PAIDTYPE_CASH)) {
					SaleCapitalDetail insertScd = new SaleCapitalDetail();
					paidCash = paidCash.add(paid.getPaidAmount());
					insertScd.setSaleBranchNo(_depOrder.getSaleBranchNo());// 销售机构号
					insertScd.setTranTime(now);
					insertScd.setTranDate(ic.getTranDate());
					insertScd
							.setTranType(SaleCapitalDetail.TRANTYPE_CANCELRECEIVECASH);// 15收到现金取消
					insertScd.setTicketId(insertPaidId);
					insertScd.setCreditDeposit(BigInteger.ZERO);
					insertScd.setCreditWithdraw(BigInteger.ZERO);
					insertScd.setCashDeposit(BigInteger.ZERO.subtract(paid
							.getPaidAmount()));// 现金存入撤销
					insertScd.setCashWithdraw(BigInteger.ZERO);
					insertScd.setOperId(webInput.getOperId());
					insertScd.setRemark("充值单现金记账撤销");
					saleCapitalDetailDaoImpl.insertSaleCapitalDetail(insertScd);
				}

				depositOrderPaidDetailDaoImpl
						.updateDepositOrderPaidDetail(paid);
			}
		}

		// 修改销售商分支机构（SaleBranch）现金库存
		SaleBranch sbs = saleBranchDaoImpl.getSaleBranchForUpdate(_depOrder
				.getSaleBranchNo());
		if (sbs == null) {
			errException("销售机构“" + _depOrder.getSaleBranchNo() + "”未找到!");
		}
		sbs.setCash(sbs.getCash().subtract((paidCash)));
		saleBranchDaoImpl.updateSaleBranch(sbs);
		// 设置撤销参数
		_depOrder.setCancelDate(ic.getTranDate());
		_depOrder.setCancelTime(commonDaoImpl.getDatabaseSysTime());
		_depOrder.setCancelOperId(webInput.getOperId());
		_depOrder.setCancelAuthOperId(depositOrder.getCancelAuthOperId());

		// 充值单状态迁移明细
		insertDepositOrderActionDetail(depositOrderId, webInput.getOperId(),
				_depOrder.getOrderStatus(),
				DepositOrder.DEPORDER_ORDERSTATUS_CANCEL,
				DepositOrderActionDetail.DEPOSITOAD_ACTIONTYPE_CANCELINPUT,
				cancelRemark);

		// 执行修改
		depositOrderDaoImpl.updateDepositOrder(_depOrder);

		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Edit, "撤销充值单业务", "充值单流水号" + depositOrderId);

		return _depOrder;
	}

	private SaleCapitalDetail getSaleCapitalDetail(
			DepositOrderPaidDetail depositOrderPaidDetail, IssueCompany ic,
			String saleBranchNo, PCPSWebInput webInput)
			throws PCPSApplicationException {
		// 只记录现金账务
		if (depositOrderPaidDetail.getPaidType() != null
				&& (depositOrderPaidDetail.getPaidType()
						.equals(SaleOrderPaidDetail.PAIDDETAIL_PAIDTYPE_CASH))) {

			// SaleBranch sbs = saleBranchDaoImpl
			// .getSaleBranchBySaleBranchNo(saleBranchNo);

			// 插入销售机构资金明细表（SaleCapitalDetail）
			SaleCapitalDetail scd = new SaleCapitalDetail();
			scd.setSaleBranchNo(saleBranchNo);// 销售机构号
			// CashUpperLimit默认为0，销售单收现金检查，超过该限额提示。
			// if (ic.getCashUpperLimit() != null
			// && ic.getCashUpperLimit().compareTo(BigInteger.ZERO) > 0) {
			// if (depositOrderPaidDetail.getPaidAmount().add(sbs.getCash())
			// .compareTo(ic.getCashUpperLimit()) > 0) {
			// errException("充值单收现后销售机构现金库为"
			// + get100(depositOrderPaidDetail.getPaidAmount()
			// .add(sbs.getCash())) + "超过发卡商现金库上限"
			// + get100(ic.getCashUpperLimit()) + ",必须转账!");
			// }
			// }
			scd.setTranDate(ic.getTranDate());
			scd.setTranType(SaleCapitalDetail.TRANTYPE_RECEIVECASH);// 05 – 收到现金
			scd.setCreditDeposit(BigInteger.ZERO);// 信用度存入 decimal(16) Not
			scd.setCreditWithdraw(BigInteger.ZERO);// 信用度支出 decimal(16) Not
			scd.setCashDeposit(depositOrderPaidDetail.getPaidAmount());// 现金存入
			scd.setCashWithdraw(BigInteger.ZERO);// 现金支出 decimal(16) Not Null
			scd.setOperId(webInput.getOperId());// 操作员ID
			scd.setRemark("充值单付款现金记账"); // 摘要
			return scd;
		}
		return null;
	}

	private DepositOrderPaidDetail getDepositOrderPaidDetail(
			PCPSWebInput webInput, DepositOrderPaidDetail depositOrderPaidDetail)
			throws PCPSApplicationException {
		// 对象为NULL
		if (depositOrderPaidDetail == null) {
			errException("充值单付款对象为NULL");
		}
		// 非现金付款必输录入付款人和购卡人
		if (!depositOrderPaidDetail.getPaidType().equals(
				DepositOrderPaidDetail.DEPOSITOPD_PAIDTYPE_CASH)) {
			if (depositOrderPaidDetail.getBankAccDetailId() == null) {
				errException("非现金充值时银行转账编号必须填写!");
			}
			BankAccountDetail bad = bankAccountDetailDaoImpl
					.getBankAccountDetailByID(depositOrderPaidDetail
							.getBankAccDetailId());
			if (bad == null) {
				errException("银行转账记账流水未找到!");
			}

			depositOrderPaidDetail.setPayeeAccountId(bad.getBankAccountId());// 发卡商银行信息
			depositOrderPaidDetail.setPaidAccountId(bad.getPaidBankAccountId());// 付款人ID
			depositOrderPaidDetail.setVoucherNo(bad.getVoucherNo());// 凭证号
			depositOrderPaidDetail.setVoucherRemark(bad.getVoucherRemark());// 凭证摘要
			depositOrderPaidDetail.setVoucherImageId(bad.getVoucherImageId());// 凭证图片Id
		}
		// 判断收款人和付款人是否为同一人
		// if (depositOrderPaidDetail.getPaidAccountId() != null
		// && depositOrderPaidDetail.getPayeeAccountId() != null) {
		// if (depositOrderPaidDetail.getPaidAccountId().intValue() ==
		// depositOrderPaidDetail
		// .getPayeeAccountId().intValue()) {
		// errException("销售单收款人和付款人不能为同一人!");
		// }
		// }
		// // 收款人
		// if (depositOrderPaidDetail.getPayeeAccountId() != null) {
		// // 收款人---->发卡商银行检查
		// List<BankAccount> baList = bankAccountDaoImpl
		// .getBankAccountDropdown(webInput,
		// BankAccount.BANKTYPE_ISSUECOMPANY);
		// boolean tag = false;
		// for (BankAccount iba : baList) {
		// if (depositOrderPaidDetail.getPayeeAccountId().compareTo(
		// iba.getBankAccountId()) == 0) {
		// tag = true;
		// }
		// }
		// if (!tag) {
		// errException("收款人银行账户不为发卡商银行账户!");
		// }
		// }
		// 付款金额
		if (depositOrderPaidDetail.getPaidAmount() == null
				|| depositOrderPaidDetail.getPaidAmount().compareTo(
						BigInteger.ZERO) <= 0) {
			errException("付款金额为空或小于0!");
		} else {
			depositOrderPaidDetail.setPaidAmount(depositOrderPaidDetail
					.getPaidAmount());
		}
		return depositOrderPaidDetail;
	}

	@EJB(mappedName = "account.impl.MasterAccountDaoImpl")
	private MasterAccountDao masterAccountDaoImpl;

	private DepositOrderDetail getDepositOrderDetail(
			DepositOrderDetail depOrdDetail, String saleType,
			BigInteger eachCardBalance, BigInteger eachCardOwnerLimit,
			Integer saleLimit) throws PCPSApplicationException {
		if (PCPSUtil.isEmpty(depOrdDetail.getCardSeqNo())) {
			errException("批量充值卡顺序号必须填写!");
		}

		if (depOrdDetail.getDepositAmount().compareTo(BigInteger.ZERO) <= 0) {
			errException("批量充值金额必须大于0!");
		}
		// 非直营时售卡限制
		if (saleType.equals(SaleBranch.SaleBranch_SaleType_Proxy)) {
			// 单卡充值不可大于该限制
			if (saleLimit.intValue() > 0) {
				if (depOrdDetail.getDepositAmount().intValue() > saleLimit
						.intValue()) {
					errException("非直属销售机构单卡充值不可大于" + saleLimit / 100 + "!");
				}
			}
		}
		ActivateCard ac = activateCardDaoImpl
				.getActivateCardByCardSeqNo(depOrdDetail.getCardSeqNo());
		BigInteger authDeposit = BigInteger.ZERO;
		if (ac.getMasterAccNo() != null) {
			authDeposit = masterAccountDaoImpl.getMasterAccountByMasterAccNo(
					ac.getMasterAccNo()).getAuthDeposit();
		} else {
			errException("卡" + ac.getCardNo() + "状态异常!");
		}
		// 判断是否为充值卡
		CardClassic cc = null;
		cc = cardClassicDaoImpl.getCardClassicByCardClassicId(ac
				.getCardClassicId());
		if (cc == null) {
			if (PCPSUtil.isEmpty(depOrdDetail.getCardNo())) {
				errException("卡号" + depOrdDetail.getCardSeqNo() + "不存在!");
			} else {
				errException("卡号" + depOrdDetail.getCardNo() + "不存在!");
			}
		} else {
			if (cc.getAllowDeposit().equals(
					CardClassic.CARDCLASSIC_ALLOWDEPOSIT_NORECHARGE)) {
				if (PCPSUtil.isEmpty(depOrdDetail.getCardNo())) {
					errException(depOrdDetail.getCardSeqNo() + "卡序号不允许充值!");
				} else {
					errException(depOrdDetail.getCardNo() + "卡号不允许充值!");
				}
			}
		}
		// 检查所有充值单卡是否合法
		if (ac == null) {
			errException("卡号" + depOrdDetail.getCardNo() + "不存在!");
		} else {
			// 非实名卡，不可充值大于实名限制，不可大于卡余额限制
			if (ac.getOwnerId() == null
					&& eachCardOwnerLimit.compareTo(BigInteger.ZERO) > 0) {
				if (ac.getBalance().add(depOrdDetail.getDepositAmount()).add(
						authDeposit).compareTo(eachCardOwnerLimit) > 0) {
					errException("非实名卡余额上限为："
							+ get100(eachCardOwnerLimit)
							+ " "
							+ ac.getCardNo()
							+ "充值待审金额加卡余额与充值金额后为"
							+ get100(ac.getBalance().add(
									depOrdDetail.getDepositAmount()).add(
									authDeposit)) + "已超出上限!");
				}
			}
			// 判断单卡余额
			if (eachCardBalance != null
					&& eachCardBalance.compareTo(BigInteger.ZERO) > 0) {
				if ((ac.getBalance().add(depOrdDetail.getDepositAmount())).add(
						authDeposit).compareTo(eachCardBalance) > 0) {
					errException("单卡余额上限为："
							+ get100(eachCardBalance)
							+ " "
							+ ac.getCardNo()
							+ "充值待审金额加卡余额与充值金额后为"
							+ get100(ac.getBalance().add(
									depOrdDetail.getDepositAmount()).add(
									authDeposit)) + "已超出上限!");
				}
			}
		}
		if (!depOrdDetail.getCardSeqNo().equals(ac.getCardSeqNo())) {
			errException("充值卡序号" + depOrdDetail.getCardSeqNo() + "与激活卡序号"
					+ ac.getCardSeqNo() + "不对应!");
		}
		// 持卡人
		depOrdDetail.setCustomId(ac.getOwnerId());
		depOrdDetail.setBatchNo(ac.getBatchNo());// 批次号
		depOrdDetail.setCardNo(ac.getCardNo());// 卡号
		depOrdDetail.setCardFaceId(ac.getCardFaceId());// 卡面
		depOrdDetail.setCardClassicId(ac.getCardClassicId());// 卡种类
		return depOrdDetail;
	}

	private DepositOrder getDepositOrder(PCPSWebInput webInput,
			DepositOrder depositOrder) throws PCPSApplicationException {
		// 插入对象为null
		if (depositOrder == null) {
			errException("充值单录入对象为空!");
		}
		if (webInput.getOperId() == null
				|| PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			errException("登录操作员所属销售机构号为空!");
		}

		// 根据销售机构判断销售商是否激活过期销售机构,销售商过期，销售商下所有分支机构全部过期
		SaleBranch sb = saleBranchDaoImpl.getSaleBranchBySaleBranchNo(webInput
				.getOperBranchNo());
		if (sb == null) {
			errException("销售机构号系统中不存在!");
		} else {
			if (sb.getStatus()
					.equals(SaleBranch.SALEBRANCH_STATUS_NOTACTIVATED)) {
				errException("销售机构“" + sb.getSaleBranchName() + "”已停用!");
			}
			depositOrder.setSaleBranchNo(webInput.getOperBranchNo());
			SysBranch sysBranch = sysBranchDaoImpl.getSysBranchByBranchNo(sb
					.getSaleBranchNo());
			if (sysBranch == null) {
				errException("登录操作员所属销售机构号平台机构表中不存在!");
			} else {
				if (!sysBranch.getBranchType().equals(
						SysBranch.SYSBRANCH_SALEBRANCH)) {
					errException("只有销售商分支机构操作员才可售卡!");
				}
			}
			if (sb.getExpired() != null) {
				if (sb.getExpired().before(commonDaoImpl.getSysDateFormatYMD())) {
					errException("该销售机构所在销售商已过期!");
				}
			}
			if (sb.getDayOff().equals(SaleBranch.In_DayOff)) {
				errException("销售机构“" + sb.getSaleBranchName() + "”已经日结!");
			}
		}
		// 个人购卡
		if (DepositOrder.DEPORDER_BUYERTYPE_PERSON.equals(depositOrder
				.getBuyerType())) {
			if (depositOrder.getPersonalBuyerId() == null
					&& depositOrder.getProxyBuyerId() == null) {
				errException("个人充值时购卡人代理人不可都为空!");
			}
		}
		// 单位购卡
		if (DepositOrder.DEPORDER_BUYERTYPE_COMPANY.equals(depositOrder
				.getBuyerType())) {
			if (depositOrder.getOrganizeBuyerId() == null) {
				errException("单位充值时单位信息不可为空!");
			}
		}
		// 黑名单验证
		// 个人信息
		if (depositOrder.getPersonalBuyerId() != null) {
			PersonalCustom pc = personalCustomDaoImpl
					.getPersonalCustomByPersonalId(depositOrder
							.getPersonalBuyerId());
			BlackList bk = new BlackList();
			bk.setIdTypeId(pc.getIdTypeId());
			bk.setIdNo(pc.getIdNo());
			if (blackListDaoImpl.getBlackListByBlackList(bk) != null) {
				errException(bk.getName() + " 已加入黑名单，禁止购卡!");
			}
		}
		// 代理人信息
		if (depositOrder.getProxyBuyerId() != null) {
			PersonalCustom pc = personalCustomDaoImpl
					.getPersonalCustomByPersonalId(depositOrder
							.getProxyBuyerId());
			BlackList bk = new BlackList();
			bk.setIdTypeId(pc.getIdTypeId());
			bk.setIdNo(pc.getIdNo());
			if (blackListDaoImpl.getBlackListByBlackList(bk) != null) {
				errException(bk.getName() + " 已加入黑名单，禁止购卡!");
			}
		}
		// 操作员号
		depositOrder.setOperId(webInput.getOperId());
		depositOrder.setBtnStatus(sb.getSaleType().trim());
		depositOrder.setTotalCheckAmount(BigInteger.ZERO);// 累计已核实资金
		return depositOrder;
	}

	/**
	 * 插入状态迁移明细
	 * 
	 * @param activeOrderId
	 * @param operId
	 * @param initialStatus
	 * @param endStatus
	 * @param actionType
	 * @param remark
	 * @throws PCPSApplicationException
	 */
	private void insertDepositOrderActionDetail(BigInteger depositOrderId,
			BigInteger operId, String initialStatus, String endStatus,
			String actionType, String remark) throws PCPSApplicationException {
		// 记录状态迁移明细
		DepositOrderActionDetail doad = new DepositOrderActionDetail();
		doad.setDepositOrderId(depositOrderId);// 充值单ID Int Not Null
		doad.setActionTime(commonDaoImpl.getDatabaseSysTime());// 操作时间 Date Not
		doad.setOperId(operId);// 操作员ID int Not Null
		doad.setInitialStatus(initialStatus);// 初始状态 char(1) Null
		doad.setEndStatus(endStatus);// 结束状态 char(1) Not Null
		doad.setActionType(actionType);// 操作类型 char(1) Not Null 0 – 结束录入
		doad.setRemark(remark);
		// 插入状态迁移明细
		depOrderAcDeDaoImpl.insertDepositOrderActionDetail(doad);
	}

	@Override
	public void updateDepositOrderVoucherNo(PCPSWebInput webInput,
			BigInteger depositOrderId, String voucherNo)
			throws PCPSApplicationException {
		String businessType = VoucherBusinessBind.BusinessType_02;
		List<VoucherBusinessBind> vbbList = voucherBusinessBindImpl
				.getVoucherBusinessBindByBusinessType(webInput, businessType,
						-1);
		if (vbbList == null || vbbList.size() < 1) {
			errException("未找到充值业务对应凭证种类!");
		}
		// 凭证种类Id
		BigInteger voucherId = vbbList.get(0).getVoucherId();
		// 插入对象为null
		if (depositOrderId == null || webInput == null
				|| PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			errException("操作员或归属机构为空!");
		}
		DepositOrder so = depositOrderDaoImpl
				.getDepositOrderForUpdate(depositOrderId);
		if (so == null) {
			errException("充值单编号错误!");
		} else {
			VoucherStock vs = new VoucherStock();
			vs.setVoucherId(voucherId);
			vs.setVoucherNo(voucherNo);
			VoucherStock serchVS = voucherStockDaoImpl.getVoucherStock(vs);
			if (serchVS == null
					|| !serchVS.getStatus().equals(VoucherStock.Status_0)) {
				// String str = (serchVS.getStatus().equals("1")) ? "在途"
				// : (serchVS.getStatus().equals("9")) ? "丢失、损坏等" : "";
				errException("凭证信息不存在或状态异常!");
			} else {
				// 更新凭证库存
				serchVS.setStatus(VoucherStock.Status_2);
				voucherStockDaoImpl.updateVoucherStockByStatus(serchVS);
				// 插入库存出入库明细
				VoucherStockDetail voucherStockDetail = new VoucherStockDetail();
				voucherStockDetail.setIoOrderId(depositOrderId);
				voucherStockDetail.setIssueCompanyNo(PCPSUtil
						.getIssueCompanyNo(webInput));
				voucherStockDetail.setBranchNo(webInput.getOperBranchNo());
				IssueCompany ic = issueCompanyDaoImpl
						.getIssueCompanyByIssueCompanyNo(PCPSUtil
								.getIssueCompanyNo(webInput));
				voucherStockDetail.setTranDate(ic.getTranDate());
				voucherStockDetail.setTranTime(commonDaoImpl
						.getDatabaseSysTime());
				voucherStockDetail.setVoucherId(voucherId);
				voucherStockDetail.setStartVoucherNo(voucherNo);
				voucherStockDetail.setEndVoucherNo(voucherNo);
				voucherStockDetail.setCount(1);
				voucherStockDetail.setTranType(VoucherStockDetail.Status_4);
				voucherStockDetail.setOperId(webInput.getOperId());

				voucherStockDetailDaoImpl
						.insertVoucherStockDetail(voucherStockDetail);
			}
			so.setVoucherId(voucherId);
			so.setVoucherNo(voucherNo);
			depositOrderDaoImpl.updateDepositOrder(so);
		}
	}
}